package hamaster.jpbc.web;

import hamaster.jpbc.IDKey;
import hamaster.jpbc.User;
import hamaster.jpbc.dao.IDKeyDAO;
import hamaster.jpbc.pbc.PBCDriver;
import hamaster.jpbc.pbc.io.BinaryIDIOImpl;
import hamaster.jpbc.pbc.io.ID;
import hamaster.jpbc.sys.IBCSystem;
import hamaster.jpbc.util.Hash;

import java.io.IOException;
import java.text.SimpleDateFormat;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * IDDownloadServlet
 */
public class IDDownloadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
     * @see HttpServlet#HttpServlet()
     */
    public IDDownloadServlet() {
    }

	/*
	 * (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String action = request.getParameter("action");
		if (!"download".equalsIgnoreCase(action)) {
			response.sendError(404);
			return;
		}
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		if (user == null) {
			response.sendError(404);
			return;
		}
		String password = request.getParameter("password");
		String hash = PBCDriver.hex(Hash.sha1(password + new SimpleDateFormat("yyMMddHHmmss").format(user.getRegDate())));
		if (!user.getPassword().equalsIgnoreCase(hash)) {
			response.sendError(404);
			return;
		}
		String keyid = request.getParameter("id");
		int id;
		try {
			id = Integer.parseInt(keyid);
		} catch (NumberFormatException e) {
			// TODO 
			return;
		}
		IDKeyDAO dao = (IDKeyDAO) IBCSystem.getBean("idKeyDAO");
		IDKey idKey = dao.get(IDKey.class, id);
		if (idKey == null) {
			// TODO 
			return;
		}
		ID idc = new BinaryIDIOImpl(idKey.getKeyContent()).load();
		response.reset();
		response.setContentType("application/octet-stream");
		response.addHeader(
				"Content-Disposition",
				"attachment; filename=\"" + idc.getPersonalParameter().getrIDString() + ".id\"");
		response.setContentLength(idKey.getKeyContent().length);
		ServletOutputStream out = response.getOutputStream();
		out.write(idKey.getKeyContent());
		out.flush();
		out.close();
	}

	/*
	 * (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

}
